package com.example.photography.Activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.photography.Model;
import com.example.photography.R;
import com.example.photography.adapter.Userinfo_adapter;
import com.example.photography.bean.User_Info;
import com.example.photography.common.AppNetConfig;
import com.example.photography.common.BaseActivity;
import com.example.photography.common.Constant;
import com.example.photography.util.SharePreference;
import com.example.photography.util.Util;
import com.example.photography.view.MyListView;
import com.example.photography.view.ZFlowLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Search_Activity extends BaseActivity {


    private final int RG_FAULT = 0;
    private final int RC_SEARCH = 1;
    private final int RQ_SUCCESS = 2;
    private final int RQ_PROBLEM = 3;
    private final int RQ_EMPTYE = 4;
    private final int INTERVAL = 500; //输入时间间隔为300毫秒
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.iv_delete)
    ImageView ivDelete;
    @BindView(R.id.zl_history)
    ZFlowLayout zlHistory;
    @BindView(R.id.lv_item)
    MyListView lvItem;

    private String message;
    private List<User_Info> user_infos = new ArrayList<>();
    private Userinfo_adapter userinfo_adapter;

    @Override
    protected void initData() {
        initView();
        initListen();
    }

    private void search_user(String url, String value) {
        //开启等待动画
//        LoadingDialog.getInstance(Search_Activity.this).show();

        OkHttpClient client = new OkHttpClient();
        //POST请求
        FormBody formBody = new FormBody.Builder()
                .add("value", value)
                .add("id_unique", value)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)                //默认就是GET请求就可以不写，这里是post
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        message = "后台君好像生病了~";
                        mHandler.sendEmptyMessageDelayed(RG_FAULT, 0);//关闭等待动画，0延时
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonString = response.body().string();
                Log.e("oooooooooooooooooooo", jsonString);
                try {
                    JSONObject jsonObject = new JSONObject(jsonString);
                    int result = Integer.parseInt(jsonObject.getString("status"));
                    message = jsonObject.getString("msg");
                    user_infos.clear();
                    if (result == 202) {//查询成功
                        JSONArray resultJsonArray = jsonObject.getJSONArray("data");
                        for (int i = 0; i < resultJsonArray.length(); i++) {
                            //循环遍历，获取json数据中data数组里的内容
                            JSONObject Object = resultJsonArray.getJSONObject(i);
                            User_Info user_info = new User_Info();
                            user_info.setId_unique(Object.getString("id_unique"));
                            user_info.setName(Object.getString("name"));
                            user_info.setHead_url(Object.getString("head_url"));
                            //保存到List集合中
                            user_infos.add(user_info);

                        }
                        mHandler.sendEmptyMessageDelayed(RQ_SUCCESS, 0);//关闭等待动画，0延时
                    } else if (result == 402) {//没查到用户
                        mHandler.sendEmptyMessageDelayed(RQ_EMPTYE, 0);//关闭等待动画，0延时
                    } else if (result == 406) {
                        mHandler.sendEmptyMessageDelayed(RQ_EMPTYE, 0);//关闭等待动画，0延时
                    } else {
                        mHandler.sendEmptyMessageDelayed(RQ_PROBLEM, 0);//关闭等待动画，0延时
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    message = e.toString();
                    mHandler.sendEmptyMessageDelayed(1, 0);//关闭等待动画，0延时

                }
            }
        });
    }


    private void initView() {
        userinfo_adapter = new Userinfo_adapter(user_infos, Search_Activity.this);
        lvItem.setAdapter(userinfo_adapter);
        search_user(AppNetConfig.user_focus, Constant.UID);
        initHistory();
    }

    private void initHistory() {
        final String[] data = SharePreference.getHistoryList();
        ViewGroup.MarginLayoutParams layoutParams = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(10, 10, 10, 10);
        zlHistory.removeAllViews();
        for (int i = 0; i < data.length; i++) {
            if ((data[i]).equals("")) {
                return;
            }
            final int j = i;
            //添加分类块
            View paramItemView = getLayoutInflater().inflate(R.layout.item_search, null);
            TextView keyWordTv = paramItemView.findViewById(R.id.tv_content);
            keyWordTv.setText(data[j]);
//            keyWordTv.setBackgroundResource(R.drawable.whitebg_strokegrey_radius3);
            zlHistory.addView(paramItemView, layoutParams);

            keyWordTv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    etSearch.setText(data[j]);
                    mHandler.sendEmptyMessageDelayed(RC_SEARCH, INTERVAL);
                }
            });
        }
    }

    private void initListen() {
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                removeCurrentActivity();
            }
        });
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String searchKey = etSearch.getText().toString().trim();
                    if (!searchKey.equals("")) {
                        SharePreference.save(searchKey);
                        mHandler.sendEmptyMessageDelayed(RC_SEARCH, INTERVAL);
                        initHistory();
                    } else {
                        Util.showToast(Search_Activity.this, "搜索内容为空~");
                    }
                    return true;
                }
                return false;
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {

                if (mHandler.hasMessages(RC_SEARCH)) {
                    mHandler.removeMessages(RC_SEARCH);
                }
                if (!TextUtils.isEmpty(etSearch.getText())) {
                    mHandler.sendEmptyMessageDelayed(RC_SEARCH, INTERVAL);
                }
            }
        });
        ivDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharePreference.cleanHistory("search_history");
                initHistory();
            }
        });

    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RG_FAULT://没网
                    Util.showToast(Search_Activity.this, message);
                    break;
                case RC_SEARCH://联网请求
                    Util.showToast(Search_Activity.this, "内容更新，联网请求~");
                    Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
                        @Override
                        public void run() {
                            search_user(AppNetConfig.user_vague, etSearch.getText().toString().trim().toString());
                        }
                    });

                    break;
                case RQ_SUCCESS:
//                    userinfo_adapter = new Userinfo_adapter(user_infos,Search_Activity.this);
//                    lvItem.setAdapter(userinfo_adapter);
//                    userinfo_adapter.refresh(user_infos);
                    userinfo_adapter.notifyDataSetChanged();
                    break;
                case RQ_EMPTYE:
                    Util.showToast(Search_Activity.this, message);
                    break;
            }
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_search;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
